package com.lanyou.esb.service;

import java.net.ConnectException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.lanyou.cook.common.Constants;
import com.lanyou.esb.exception.BundleActionException;
import com.lanyou.esb.exception.ServerMixException;
import com.lanyou.esb.servicemix.bean.Log;
import com.lanyou.esb.servicemix.monitor.ESBServer;
import com.lanyou.esb.servicemix.monitor.ESBServerFactory;
import com.lanyou.esb.servicemix.monitor.rest.MonitorService;
import com.lanyou.esb.servicemix.monitor.rest.bean.LogResponse;
import com.lanyou.esb.servicemix.util.ConnetServerTest;
import com.lanyou.esb.web.param.SystemLogLevelManagementParam;

/**
 * ServiceMix系统日志级别管理<br>
 * 
 * 
 * @author Davey.wu
 */
@Service
public class SystemLogLevelManagementService {
	@Autowired
	private ESBServerFactory esbServerFactory;

	private static FastDateFormat FASTDATEFORMAT_YYYYMMDDHHMMSS = FastDateFormat
			.getInstance(Constants.DATETIME_PATTERN_1);

	/**
	 * 获取SERVICEMIX日志,分页
	 * 
	 * @param param
	 * @param pageable
	 * @return
	 * @throws BundleActionException
	 */
	public Page<Log> findSystemLogLevelInfos(
			SystemLogLevelManagementParam param, Pageable pageable)
			throws BundleActionException {
		// 未选择任何节点，返回空集
		if (StringUtils.isBlank(param.getServiceMixIp())) {
			return new PageImpl<Log>(new ArrayList<>(0), pageable, 0);
		}
		List<Log> logs = findSystemLogLevelInfos(param);
		// 分页
		int startIndex = pageable.getPageNumber() * pageable.getPageSize();
		int toIndex = startIndex + pageable.getPageSize();

		if (logs == null || logs.isEmpty() || startIndex >= logs.size()) {
			return new PageImpl<Log>(new ArrayList<>(0), pageable, 0);
		}
		List<Log> result = logs.subList(startIndex,
				toIndex < logs.size() ? toIndex : logs.size());

		return new PageImpl<Log>(result, pageable, logs.size());
	}

	/**
	 * 获取SERVICEMIX日志
	 * 
	 * @param param
	 * @return
	 * @throws BundleActionException
	 */
	public List<Log> findSystemLogLevelInfos(SystemLogLevelManagementParam param)
			throws BundleActionException {
		LogResponse logR = null;
		try {
			MonitorService monitorService = getServiceMixServer(param
					.getServiceMixIp());
			logR = monitorService.logs(param.getLevel());
		} catch (Exception e) {
			if (e.getCause() instanceof ConnectException) {
				throw new BundleActionException("连接ServiceMix引擎失败", 0);
			} else {
				throw new BundleActionException(e.getMessage(), 0);
			}
		}
		List<Log> logs = logR.getData();
		if (logs == null) {
			return new ArrayList<>(0);
		}
		int size = logs.size();
		for (int i = size - 1; i >= 0; --i) {
			Log log = logs.get(i);
			if (!compare(log, param)) {
				logs.remove(i);
			}
		}
		return logs;
	}

	/**
	 * 比较日志是否符合查询条件
	 * 
	 * @param log
	 * @param param
	 * @return
	 */
	private boolean compare(Log log, SystemLogLevelManagementParam param) {
		// 对BUNDLE名称筛选
		if (StringUtils.isNotBlank(param.getBundleName())) {
			if (StringUtils.isBlank(log.getBundleName())) {
				return false;
			}
			if (!log.getBundleName().toUpperCase().contains(param.getBundleName().toUpperCase())) {
				return false;
			}
		}
//		// 对服务筛选
//		if (StringUtils.isNotBlank(param.getService())) {
//			if (StringUtils.isBlank(log.getService())) {
//				return false;
//			}
//			if (!log.getService().contains(param.getService())) {
//				return false;
//			}
//		}
		// 对接收开始时间筛选
		if (StringUtils.isNotBlank(param.getStartReceivedTime())) {
			if (StringUtils.isBlank(log.getReceived())) {
				return false;
			}
			try {
				Date received = new Date();
				received.setTime(Long.parseLong(log.getReceived()));
				received = FASTDATEFORMAT_YYYYMMDDHHMMSS
						.parse(FASTDATEFORMAT_YYYYMMDDHHMMSS.format(received));
				Date start = FASTDATEFORMAT_YYYYMMDDHHMMSS.parse(param
						.getStartReceivedTime());
				if (received.before(start)) {
					return false;
				}
			} catch (ParseException e) {
				return false;
			}
		}
		// 对接收结束时间筛选
		if (StringUtils.isNotBlank(param.getEndReceivedTime())) {
			if (StringUtils.isBlank(log.getReceived())) {
				return false;
			}
			try {
				Date received = new Date();
				received.setTime(Long.parseLong(log.getReceived()));
				received = FASTDATEFORMAT_YYYYMMDDHHMMSS
						.parse(FASTDATEFORMAT_YYYYMMDDHHMMSS.format(received));
				Date start = FASTDATEFORMAT_YYYYMMDDHHMMSS.parse(param
						.getEndReceivedTime());
				if (received.after(start)) {
					return false;
				}
			} catch (ParseException e) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 根据IP获取服务
	 * 
	 * @param ip
	 *            ：IP地址
	 * @return
	 * @throws ServerMixException
	 */
	private MonitorService getServiceMixServer(String ip)
			throws ServerMixException {
		ESBServer server = esbServerFactory.getESBServer(ip);
		if (server == null) {
			throw new ServerMixException("连接不上ServiceMix服务器", 0);
		}
		if (!ConnetServerTest.telnetConnect(server.getServerAddres(),
				server.getPort() + "")) {
			throw new ServerMixException("连接不上ServiceMix服务器", 0);
		}
		return server.getRestFactory().getMonitorService();
	}

}
